import subprocess

def safely_run_cmd(cmd: str, encoding='gbk') -> str:
    """ 执行一个命令，返回输出，并处理异常 """
    print(f'>>> Executing: {cmd} <<<')
    try:
        proc = subprocess.Popen(args=cmd,
                                shell=True,
                                stdin=subprocess.PIPE,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
        proc.stdin.close()
        proc.wait()
        text = proc.stdout.read()
        res = text.decode(encoding)
    except Exception as e:
        res = str(e)
    return res